{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "# Test Access to Earth Engine\n",
    "\n",
    "Run the code blocks below to test if the notebook server is authorized to communicate with the Earth Engine backend servers."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "First, check if the IPython Widgets library is available on the server."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "codeCollapsed": false,
    "collapsed": false,
    "deletable": true,
    "editable": true,
    "hiddenCell": false
   },
   "outputs": [],
   "source": [
    "# Code to check the IPython Widgets library.\n",
    "try:\n",
    "  import ipywidgets\n",
    "except ImportError:\n",
    "  print('The IPython Widgets library is not available on this server.\\n'\n",
    "        'Please see https://github.com/jupyter-widgets/ipywidgets '\n",
    "        'for information on installing the library.')\n",
    "  raise\n",
    "print('The IPython Widgets library (version {0}) is available on this server.'.format(\n",
    "  ipywidgets.__version__\n",
    "))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "Next, check if the Earth Engine API is available on the server."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "codeCollapsed": false,
    "collapsed": false,
    "deletable": true,
    "editable": true,
    "hiddenCell": false
   },
   "outputs": [],
   "source": [
    "# Code to check the Earth Engine API library.\n",
    "try:\n",
    "  import ee\n",
    "except ImportError:\n",
    "  print('The Earth Engine Python API library is not available on this server.\\n'\n",
    "        'Please see https://developers.google.com/earth-engine/python_install '\n",
    "        'for information on installing the library.')\n",
    "  raise\n",
    "print('The Earth Engine Python API (version {0}) is available on this server.'.format(\n",
    "  ee.__version__\n",
    "))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "Finally, check if the notebook server is authorized to access the Earth Engine backend servers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "codeCollapsed": false,
    "collapsed": false,
    "deletable": true,
    "editable": true,
    "hiddenCell": false
   },
   "outputs": [],
   "source": [
    "# Code to check if authorized to access Earth Engine.\n",
    "import cStringIO\n",
    "import os\n",
    "import urllib\n",
    "from IPython import display\n",
    "\n",
    "# Define layouts used by the form.\n",
    "row_wide_layout = ipywidgets.Layout(flex_flow=\"row nowrap\", align_items=\"center\", width=\"100%\")\n",
    "column_wide_layout = ipywidgets.Layout(flex_flow=\"column nowrap\", align_items=\"center\", width=\"100%\")\n",
    "column_auto_layout = ipywidgets.Layout(flex_flow=\"column nowrap\", align_items=\"center\", width=\"auto\")\n",
    "\n",
    "form_definition = {'form': None}\n",
    "response_box = ipywidgets.HTML('')\n",
    "\n",
    "def isAuthorized():\n",
    "  try:\n",
    "    ee.Initialize()\n",
    "    test = ee.Image(0).getInfo()\n",
    "  except:\n",
    "    return False\n",
    "  return True\n",
    "\n",
    "def ShowForm(auth_status_button, instructions):\n",
    "  \"\"\"Show a form to the user.\"\"\"\n",
    "  form_definition['form'] = ipywidgets.VBox([\n",
    "    auth_status_button,\n",
    "    instructions,\n",
    "    ipywidgets.VBox([response_box], layout=row_wide_layout)\n",
    "  ], layout=column_wide_layout)\n",
    "  display.display(form_definition.get('form'))\n",
    "\n",
    "def ShowAuthorizedForm():\n",
    "  \"\"\"Show a form for a server that is currently authorized to access Earth Engine.\"\"\"\n",
    "  def revoke_credentials(sender):\n",
    "    credentials = ee.oauth.get_credentials_path()\n",
    "    if os.path.exists(credentials):\n",
    "      os.remove(credentials)\n",
    "    response_box.value = ''\n",
    "    Init()\n",
    "  \n",
    "  auth_status_button = ipywidgets.Button(\n",
    "    layout=column_wide_layout,\n",
    "    disabled=True,\n",
    "    description='The server is authorized to access Earth Engine',\n",
    "    button_style='success',\n",
    "    icon='check'\n",
    "  )\n",
    "  \n",
    "  instructions = ipywidgets.Button(\n",
    "    layout = row_wide_layout,\n",
    "    description = 'Click here to revoke authorization',\n",
    "    disabled = False,\n",
    "  )\n",
    "  instructions.on_click(revoke_credentials)\n",
    "  \n",
    "  ShowForm(auth_status_button, instructions)\n",
    "\n",
    "def ShowUnauthorizedForm():\n",
    "  \"\"\"Show a form for a server that is not currently authorized to access Earth Engine.\"\"\"\n",
    "\n",
    "  auth_status_button = ipywidgets.Button(\n",
    "    layout=column_wide_layout,\n",
    "    button_style='danger',\n",
    "    description='The server is not authorized to access Earth Engine',\n",
    "    disabled=True\n",
    "  )\n",
    "    \n",
    "  auth_link = ipywidgets.HTML(\n",
    "    '<a href=\"{url}\" target=\"auth\">Open Authentication Tab</a><br/>'\n",
    "    .format(url=ee.oauth.get_authorization_url()\n",
    "    )\n",
    "  )\n",
    "    \n",
    "  instructions = ipywidgets.VBox(\n",
    "    [\n",
    "      ipywidgets.HTML(\n",
    "        'Click on the link below to start the authentication and authorization process. '\n",
    "        'Once you have received an authorization code, use it to replace the '\n",
    "        'REPLACE_WITH_AUTH_CODE in the code cell below and run the cell.'\n",
    "      ),\n",
    "      auth_link,\n",
    "    ],\n",
    "    layout=column_auto_layout\n",
    "  )\n",
    "  \n",
    "  ShowForm(auth_status_button, instructions)\n",
    "  \n",
    "def Init():\n",
    "  # If a form is currently displayed, close it.\n",
    "  if form_definition.get('form'):\n",
    "    form_definition['form'].close()\n",
    "  # Display the appropriate form according to whether the server is authorized.\n",
    "  if isAuthorized():\n",
    "    ShowAuthorizedForm()\n",
    "  else:\n",
    "    ShowUnauthorizedForm()\n",
    "    \n",
    "Init()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If the server **is authorized**, you do not need to run the next code cell.\n",
    "\n",
    "If the server **is not authorized**:\n",
    "\n",
    "1. Copy the authentication code generated in the previous step.\n",
    "2. Replace the REPLACE_WITH_AUTH_CODE string in the cell below with the authentication code.\n",
    "3. Run the code cell to save authentication credentials."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "auth_code = 'REPLACE_WITH_AUTH_CODE'\n",
    "\n",
    "response_box = ipywidgets.HTML('')\n",
    "try:\n",
    "  token = ee.oauth.request_token(auth_code.strip())\n",
    "  ee.oauth.write_token(token)\n",
    "  if isAuthorized():\n",
    "    Init()\n",
    "  else:\n",
    "    response_box.value = '<font color=\"red\">{0}</font>'.format(\n",
    "      'The account was authenticated, but does not have permission to access Earth Engine.'\n",
    "    )\n",
    "except Exception as e:\n",
    "  response_box.value = '<font color=\"red\">{0}</font>'.format(e)\n",
    "response_box"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "Once the server is authorized, you can retrieve data from Earth Engine and use it in the notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "codeCollapsed": false,
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Code to display an Earth Engine generated image.\n",
    "from IPython.display import Image\n",
    "\n",
    "url = ee.Image(\"CGIAR/SRTM90_V4\").getThumbUrl({'min':0, 'max':3000})\n",
    "Image(url=url)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
